package com.zx.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;


/**
 * @author cql
 * @date 2021/7/28
 */
public class LoginInterceptor implements HandlerInterceptor {
    private static String loginUrl="login.jsp";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String uri = String.valueOf(request.getRequestURL());
        System.out.println(uri);
        if (uri.contains("login")||uri.contains("register")|| uri.equals("findAccount")) {
            return true;
        } else {
            HttpSession session = request.getSession();
            Object uid = session.getAttribute("uid");
            if (uid != null) {
                return true;
            } else {
                System.out.println(isAjaxRequest(request, response));
                if(isAjaxRequest(request, response)){
                    ajaxHttpToLogin(request,response,loginUrl);
                }else {
                   request.getRequestDispatcher("/SSM/login.jsp").forward(request,response);
                }
                return false;
            }
        }
    }


    /**
     * 判断是否为ajax请求
     *
     * @param request
     * @param response
     * @return
     */
    private boolean isAjaxRequest(HttpServletRequest request, HttpServletResponse response) {
        try {
            //判断是否为ajax请求。
            if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private void ajaxHttpToLogin(HttpServletRequest request, HttpServletResponse response, String loginUrl) {
        try {
            response.setHeader("CONTEXTPATH", loginUrl);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
